package com.sicnu.startup.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * @author zr
 * @date 2022/1/8 9:39
 */
@Controller
@CrossOrigin
public class CodeController {
    @Autowired
    private Producer captchaProducer = null;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("imageCode", capText);
        // 这里我们使用redis缓存验证码的值，并设置过期时间为60秒
//        stringRedisTemplate.opsForValue().set("imageCode", capText, 120, TimeUnit.SECONDS);
        //向客户端写出
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}

